package cn.jingyuan.swan.system.service.impl;

import cn.jingyuan.bee.utils.StringUtils;
import cn.jingyuan.swan.system.domain.gateway.dao.GatewayAccessLogDao;
import cn.jingyuan.swan.system.domain.gateway.entity.GatewayAccessLog;
import cn.jingyuan.swan.system.service.GatewayAccessLogService;
import cn.jingyuan.swan.system.service.IpRegionService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class GatewayAccessLogServiceImpl implements GatewayAccessLogService {

    @Resource
    GatewayAccessLogDao accessLogDao;

    @Resource
    IpRegionService ipRegionService;

    @Override
    public Long save(GatewayAccessLog accessLog) {
        Date now = new Date();

        String region = null;
        if (StringUtils.isNotBlank(accessLog.getIp())) {
            region = ipRegionService.getRegion(accessLog.getIp());
        }

        accessLog
            .setRegion(region)
            .setUseTime(accessLog.getResponseTime().getTime() - accessLog.getRequestTime().getTime())
            .setCreateTime(now)
            .setUpdateTime(now);

        accessLogDao.insert(accessLog);

        return accessLog.getAccessId();
    }

}
